<template>
    <div class="app-container">
        <el-card shadow="hover">
            <div class="deviceCategoty-search mb15">
                <el-form :inline="true" size="default" label-width="68px">
                    <el-form-item label="数据名称" prop="name">
                        <el-input v-model="queryParams.name" placeholder="请输入数据名称" clearable
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="数据标识" prop="mark">
                        <el-input v-model="queryParams.mark" placeholder="请输入数据标识" clearable
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="数据类型" prop="dataType">
                        <el-select v-model="queryParams.dataType" placeholder="请选择数据类型" clearable>
                            <el-option v-for="dict in data_type_dict"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">
                            <el-icon>
                                <ele-Search />
                            </el-icon>
                            查询
                        </el-button>
                           </el-form-item>
            <el-form-item style="vertical-align: top;">
                        <el-button @click="resetQuery">
                            <el-icon>
                                <ele-Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <ele-FolderAdd />
                            </el-icon>
                            新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" :disabled="single" @click="handleUpdate">
                            <el-icon>
                                <ele-Edit />
                            </el-icon>
                            修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" :disabled="multiple" @click="handleDelete">
                            <el-icon>
                                <ele-Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </el-col>
                </el-row>
            </div>
        </el-card>
        <el-table v-loading="loading" :data="deviceCategotyList" @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="数据名称" align="center" prop="name" />
            <el-table-column label="数据标识" align="center" prop="mark" />
            <el-table-column label="数据类型" align="center" prop="dataType" :formatter="dataTypeFormat"/>
            <el-table-column label="数据单位" align="center" prop="unit" />
            <el-table-column label="变比系数" align="center" prop="ratio" />
            <el-table-column label="格式化显示" align="center" prop="format" />
            <el-table-column label="首页是否展示" align="center" prop="homeShow" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" class="no_padding" size="small" @click="handleUpdate(scope.row)">修改
                    </el-button>
                    <el-button type="text" class="no_padding" size="small" @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="deviceCategotyList" />
        <!-- 添加或修改设备类别对话框 -->
        <el-dialog :title="title" v-model="open" width="769px">
            <template #header>
                <div> {{ title }}</div>
            </template>
            <el-form :model="ruleForm" ref="formRef" :rules="rules" size="default" label-width="120px">
                <el-form-item label="数据名称" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入数据名称" />
                </el-form-item>
                <el-form-item label="数据标识" prop="mark">
                    <el-input v-model="ruleForm.mark" placeholder="请输入数据标识" />
                </el-form-item>
                <el-form-item label="数据类型" prop="dataType">
                    <el-select v-model="ruleForm.dataType" placeholder="请选择数据类型">
                        <el-option v-for="dict in data_type_dict"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据单位" prop="unit">
                    <el-input v-model="ruleForm.unit" placeholder="请输入数据单位" />
                </el-form-item>
                <el-form-item label="变比系数" prop="ratio">
                    <el-input v-model="ruleForm.ratio" placeholder="请输入变比系数" />
                </el-form-item>
                <el-form-item label="格式化显示" prop="format">
                    <el-input v-model="ruleForm.format" placeholder="请输入格式化显示" />
                </el-form-item>
                <el-form-item label="首页是否展示" prop="homeShow">
                    <el-input v-model="ruleForm.homeShow" placeholder="请输入首页是否展示" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCancel" size="default">取 消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { defineComponent, getCurrentInstance, onMounted, reactive, ref, toRefs, unref } from 'vue';
import {
    listDeviceCategoty,
    getDeviceCategoty,
    delDeviceCategoty,
    addDeviceCategoty,
    updateDeviceCategoty,
} from "/@/api/device/deviceCategoty";
import { useRouter } from 'vue-router';
import { selectDictLabel } from "/@/utils/common";
import { getDataList } from "/@/api/system/dict/data";
interface DeviceCategotyDataState {
    ids: number[];
    loading: boolean;
    // 选中表数组
    // tableNames: any[];
    // 非单个禁用
    single: boolean;
    // 非多个禁用
    multiple: boolean;
    total: number;
    // 设备类别表格数据
    deviceCategotyList: any[],
    kindInfo:any;
    title: string;
    open: boolean;
    ruleForm: any;
    data_type_dict:any;
    queryParams: {
        pageNum: number;
        pageSize: number;
        kindId: any,
        name: any,
        mark: any,
        dataType: any,
        unit: any,
        ratio: any,
        format: any,
        homeShow: any,
    };
    rules: any;
}
export default defineComponent({
    components: {},
    name: 'DeviceCategoty',
    setup() {
        const { proxy } = <any>getCurrentInstance();
        const formRef = ref<HTMLElement | null>(null);
        const router = useRouter();
        //const {}
        const state = reactive<DeviceCategotyDataState>({
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            data_type_dict:{},
            // 设备类别表格数据
            deviceCategotyList: [],
            kindInfo:{},
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                kindId: undefined,
                name: undefined,
                mark: undefined,
                dataType: undefined,
                unit: undefined,
                ratio: undefined,
                format: undefined,
                homeShow: undefined,
            },
            // 表单参数
            ruleForm: {},
            // 表单校验
            rules: {
                name: [
                    { required: true, message: "数据名称不能为空", trigger: "blur" }
                ],
            }
        });
        /** 查询设备类别列表 */
        const handleGetList = () => {
            state.loading = true;

            getDataList({"dictType":"data_type"}).then((res: any) => {
                let dict:any = res.data.list;
                if(dict)
                {
                   state.data_type_dict = dict.map((p:any) =>  ({ label: p.dictLabel, value: p.dictValue, isDefault: p.isDefault }));
                }
             });

            listDeviceCategoty(state.queryParams).then((res: any) => {
                state.deviceCategotyList = res.data.list;
                state.kindInfo = res.data.kind;
                state.total = res.data.total;
                state.loading = false;
            });

            if(state.kindInfo ==  undefined || state.kindInfo.length <= 0 )
            {
                ElMessageBox.alert('产品模板不存在', '提示', {});
                //router.push('/device/deviceKind/list');
                //proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...router }));
            }
        };

         const dataTypeFormat=(row:any) => {
            return selectDictLabel(state.data_type_dict, row.dataType);
            };

        // 取消按钮dataType
        const handleCancel = () => {
            state.open = false;
            handleReset();
        };
        // 表单重置
        const handleReset = () => {
            state.ruleForm = {
                kindId:state.kindInfo.id,
                name: undefined,
                mark: undefined,
                dataType: undefined,
                unit: undefined,
                ratio: undefined,
                format: undefined,
                homeShow: undefined,
                remark: undefined,
                createdAt: undefined,
                updatedAt: undefined,
            };
            // resetForm("form");
        };
        /** 搜索按钮操作 */
        const handleQuery = () => {
            state.queryParams.pageNum = 1;
            handleGetList();
        };
        /** 重置按钮操作 */
        const resetQuery = () => {
            //resetForm("queryForm");
            handleQuery();
        };
        // 多选框选中数据
        const handleSelectionChange = (selection: any) => {
            state.ids = selection.map((item: any) => item.id)
            state.single = selection.length != 1
            state.multiple = !selection.length
        };
        /** 新增按钮操作 */
        const handleAdd = () => {
            handleReset();
            state.open = true;
            state.title = "添加设备类别";
        };
        /** 修改按钮操作 */
        const handleUpdate = (row: any) => {
            handleReset();
            const id = row.id || state.ids
            getDeviceCategoty(id).then((res: any) => {
                let data = res.data;
                data.dataType = '' + data.dataType
                state.ruleForm = data;
                state.open = true;
                state.title = "修改设备类别";
            });
        };
        /** 提交按钮 */
        const submitForm = () => {
            //const formWrap = unref(formRef) as any;
            proxy.$refs.formRef.validate((valid: boolean) => {
                if (valid) {
                    if (state.ruleForm.id != undefined) {
                        state.ruleForm.kindId = state.kindInfo.id;
                        updateDeviceCategoty(state.ruleForm).then((res: any) => {
                            if (res.code === 0) {
                                ElMessage.success("修改成功");
                                state.open = false;
                                handleGetList();
                            } else {
                                ElMessage.error(res.msg);
                            }
                        });
                    } else {
                        state.ruleForm.kindId = state.kindInfo.id;
                        addDeviceCategoty(state.ruleForm).then((res: any) => {
                            if (res.code === 0) {
                                ElMessage.success("新增成功");
                                state.open = false;
                                handleGetList();
                            } else {
                                ElMessage.error(res.msg);
                            }
                        });
                    }
                }
            });
        };
        /** 删除按钮操作 */
        const handleDelete = (row: any) => {
            const ids = row.id || state.ids;
            ElMessageBox.confirm('是否确认删除设备类别编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delDeviceCategoty(ids);
            }).then(() => {
                handleGetList();
                ElMessage.success("删除成功");
            }).catch(function () { });
        };
        // 页面加载时
        onMounted(() => {
            state.queryParams.kindId = router.currentRoute.value.query["kindId"];
            if(state.queryParams.kindId ==  undefined || state.queryParams.kindId.length <= 0 ||state.queryParams.kindId < 1)
            {
                ElMessageBox.alert('参数错误！', '提示', {});
               // router.push('/device/deviceKind/list');
               // proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...router }));
            }else
            {
                handleGetList();
            }
            
        });
        return {
            router,
            formRef,
            //data_type_dict,
            dataTypeFormat,
            handleGetList,
            handleCancel,
            handleReset,
            handleQuery,
            resetQuery,
            handleSelectionChange,
            handleAdd,
            handleUpdate,
            submitForm,
            handleDelete,
            ...toRefs(state),
        };
    }
});
</script>